define(function (require, exports, module) {
    require("ie/ie-shim.js").init();
    
    var $ = require('jquery');
    require('jquery/jqueryui/jquery-ui.min.js');
    require('validate');
    require('jquery/placeholder.js');
    var regTest = require('./regTest.js');
    require('cookie');
    $.fn.placeholder();

    if (!window.i18n) { 

        var i18nx = require("i18next");
        i18nx.init({
            lng: $.cookie("i18next") || "zh-CN",
            fallbackLng: false,
            load: 'current'
        }, function (t) {
            LoadContent();
        });
        window.i18n = i18nx;
    } else {
        LoadContent();
    }

    function LoadContent(){
        //涉黄应用
        if(location.search.slice(1).indexOf('type=1') > -1){
            $('#notice').show();
        }

        var errors=require("msmErrors");
        var utils = require('./utils.js');
        var lang = $.cookie('i18next');
        if(lang){
            if($("#langSelect")[0]){
                $("#langSelect").find('option:selected')[0].selected = false;
                $("#langSelect").find('option[value="'+ lang +'"]')[0].selected = true;
            }
        }
        //切换语言
        $("#langSelect").on("change",function(){
            i18n.setLng($(this).val());
            location.reload();
        });

        utils.placeholderForPwd($('input[type="password"]'),{
            left: 0,
            top: 0,
            color: '#555',
            'text-indent': '44px',
            'font-weight': 'normal',
            'font-size': '14px'
        });
        // 验证码部分
        var changeCcap = function(){
            $('.ccap').attr('src', '/getccap?'+(Math.random()+'').replace('.',''));
        };
        $('.ccap').on('click', function(event) {
            changeCcap();
            event.preventDefault();
        });
        // changeCcap();
        // 验证码部分 end
        // 自动填充
        if ($.cookie('autoWEmail')) {
            $('#username').val($.cookie('autoWEmail'));
            $.removeCookie('autoWEmail');
        }
        $('label.a').on('click', function(event) {
            if ($(this).hasClass('active')) {
                $(this).removeClass('active')
            } else{
                $(this).addClass('active')
            }
            event.preventDefault();
        });

        // 是否需要填写完整信息modal go_profile_modal
        function linkToPage(){
            var rememberMe = 0;
            if($('label.a').hasClass('active')){
                rememberMe = 1;
            }
            setTimeout(function() {
                $('#submit').removeAttr('disabled');
                if (rememberMe) {
                    $.cookie('remMe', 'true', {
                        expires: 7
                    });
                    $.cookie('username', emailForNote,{
                        expires: 30
                    });
                } else{
                    $.cookie('username', emailForNote,{
                        expires: 1
                    });
                }
                var redirectUrl = window.location.search;
                if (redirectUrl) {
                    var newUrl = redirectUrl.split('=')[1];
                }
                if (newUrl) {
                    window.location.href = newUrl;
                } else {
                    window.location.href = '/console';
                }
            }, 2000);
        };
        // 个人资料填写完整
        var emailForNote;
        $('#go_profile_modal').on('click', '.ensure', function(event) {
            // 不再提示的实现
            if ($('.tips-label').hasClass('active')) {
                $.ajax({
                    url: '/user/note',
                    type: 'GET',
                    dataType: 'json',
                    data: {
                        email: emailForNote
                    }
                })
                .done(function(data) {
                    if (data && data.status) {
                        linkToPage();
                    } else{}
                })
                .fail(function() {
                })
                .always(function() {
                });
                
            } else{
                linkToPage();
            }
            event.preventDefault();
        });
        $('#go_profile_modal .tips-label').on('click', function(event) {
            $(this).toggleClass('active');
            event.preventDefault();
        });
        var options = {
            dialogClass: 'go_profile_dialog',
            title: i18n.t('common.signinTips'),
            resizable: false,
            minHeight: 220,
            minWidth: 500,
            modal: true,
            close: function(){
                if (!$('.tips-label').hasClass('active')){
                    linkToPage();
                }
                
            }
        };
        $.validator.addMethod('loginName', function(value, element, param) {
            var regTrim = /\s/g;
            var $this = $(element);
            $this.val($this.val().replace(regTrim,''));
            value = value.replace(regTrim, '');
            
            var regPhone = regTest.phone;
            var regEmail = regTest.email;
            if (regPhone.test(value) || regEmail.test(value)) {
                regPhone.lastIndex = 0;
                regEmail.lastIndex = 0;
                return true
            } else{
                regPhone.lastIndex = 0;
                regEmail.lastIndex = 0;
                return false;
            }
            
        }, i18n.t('common.errorEmail&Mobile'));

        $('#loginFrm').validate({
            errorPlacement: function (error, element) {
                $(element).parents('.form-group').find('.err-popover-content').html(error);
            },
            rules: {
                username: {
                    required: true,
                    loginName: true
                },
                password: {
                    required: true,
                    rangelength: [6,16]
                },
                ccap: {
                    required: true
                }
            },
            messages: {
                username: {
                    required: i18n.t('common.emptyEmail&Mobile')
                },
                password: {
                    required: i18n.t('error.A00005'),
                    rangelength: i18n.t('error.A00006')
                },
                ccap: {
                    required: i18n.t('appInfo.notice14')
                }
            },
            highlight: function(element, errorClass){
                $(element).addClass('error');
                $(element).parents('.form-group').find('.err-popover').addClass('active');
            },
            unhighlight: function(element, errorClass){
                $(element).removeClass('error');
                $(element).parents('.form-group').find('.err-popover').removeClass('active');
            },
            submitHandler: function(form) {
                // 验证码
                var value = $('#ccap-text').val();
                var key = $('#username').val();
                // var password = utils.md5($('#password').val());
                var password = $('#password').val();
                var rememberMe = 0;
                if($('label.a').hasClass('active')){
                    rememberMe = 1;
                }
                
                var signin = function(){
                    $('#submit').attr('disabled', 'disabled');
                    // 登录
                    $.ajax({
                        url: '/api/userlogin.html',
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            key: key,
                            password: password,
                            captcha: value,
                            rememberMe: rememberMe
                        }
                    })
                    .done(function(data) {
                        // 需新增补全资料的建议
                        if (data && data.status == 1) {
                            //BBS login
                            var bbsFrm = $('#bbsLogin')[0].contentWindow.document.getElementById('bbsFrm');
                            var $usr = $(bbsFrm).find('[name="username"]');
                            var $pwd = $(bbsFrm).find('[name="pwd"]');
                            $usr.val(data.result.email);
                            $pwd.val(password);
                            bbsFrm.submit();
                            emailForNote = data.result.email;
                            if (data.result.note == 1) {
                                // 不提示
                                setTimeout(function() {
                                    $('#submit').removeAttr('disabled');
                                    if (rememberMe) {
                                        $.cookie('remMe', 'true', {
                                            expires: 7
                                        });
                                        $.cookie('username', emailForNote,{
                                            expires: 30
                                        });
                                    } else{
                                        $.cookie('username', emailForNote,{
                                            expires: 1
                                        });
                                    }
                                    var redirectUrl = window.location.search;
                                    if (redirectUrl) {
                                        var newUrl = redirectUrl.split('=')[1];
                                    }
                                    if (newUrl) {
                                        window.location.href = newUrl;
                                    } else {
                                        window.location.href = '/console';
                                    }
                                }, 2000);
                            } else{
                                if (data.result.data == 0) {
                                    $('#go_profile_modal').dialog(options);
                                } else{
                                    // 与上面相同，可以考虑提出来
                                    setTimeout(function() {
                                        $('#submit').removeAttr('disabled');
                                        if (rememberMe) {
                                            $.cookie('remMe', 'true', {
                                                expires: 7
                                            });
                                            $.cookie('username', emailForNote,{
                                                expires: 30
                                            });
                                        } else{
                                            $.cookie('username', emailForNote,{
                                                expires: 1
                                            });
                                        }
                                        var redirectUrl = window.location.search;
                                        if (redirectUrl) {
                                            var newUrl = redirectUrl.split('=')[1];
                                        }
                                        if (newUrl) {
                                            window.location.href = newUrl;
                                        } else {
                                            window.location.href = '/console';
                                        }
                                    }, 2000);
                                }
                            }
                        } else{
                            $('#submit').removeAttr('disabled');

                            utils.alertMessage(0,errors.msmTip[data.code]);
                            changeCcap();
                        }
                    })
                    .fail(function(data) {
                    })
                    .always(function(data){
                    });
                    // 登录 end
                };
                signin();

                // $.ajax({
                //     url: '/checkccap',
                //     type: 'POST',
                //     data: {
                //         'validCode': value
                //     },
                //     async: true,
                //     success: function(data){
                //         var data = eval('('+data+')');
                //         if (data.status == 1){
                //             $('#ccap-text').removeClass('error');
                //             $('#ccap-text').parents('.form-group').find('.err-popover').removeClass('active');
                //             $('#submit').attr('disabled', 'disabled');
                //             signin();
                //         } else {
                //             changeCcap();
                //             $('#ccap-text').addClass('error');
                //             $('#ccap-text').parents('.form-group').find('.err-popover').addClass('active');
                //             $('#ccap-text').parents('.form-group').find('.err-popover-content').html('<label class="error">'+ i18n.t('appInfo.notice15') +'</label>');
                //             return;
                //         }
                //     }
                // });
                // 验证码 end
                
                return false;
            }
        });

    }
    exports.init = function(){};
    
});
